package com.bite.blog.controller;

import com.bite.blog.enums.ResponseCodeEnum;
import com.bite.blog.enums.TokenPropEnum;
import com.bite.blog.model.Response;
import com.bite.blog.model.User;
import com.bite.blog.service.UserService;
import com.bite.blog.utils.JwtUtils;
import com.bite.blog.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Response<?> login(String userName, String password) {

        log.info("用户登录 login userName: {}", userName);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            log.warn("用户名或密码为空");
            return Response.fail(ResponseCodeEnum.FAIL.getCode(), "用户名或密码不能为空");
        }

        User user = userService.login(userName);
        if (user == null || user.getId() == null || user.getPassword() == null) {
            return Response.fail(ResponseCodeEnum.PARAM_INVALID.getCode(), "输入参数不合法");
        }

        if (!SecurityUtils.verity(password, user.getPassword())) {
            log.warn("密码错误");
            return Response.fail(ResponseCodeEnum.FAIL.getCode(), "密码错误");
        }

        // 用户名和密码校验成功 获取token
        Map<String, Object> claims = new HashMap<>();
        claims.put(TokenPropEnum.USER_NAME.getProp(), user.getUserName());
        claims.put(TokenPropEnum.USER_ID.getProp(), user.getId());
        String jwt = JwtUtils.getJwt(claims);
        return Response.success(jwt);
    }

    @RequestMapping("/getUserInfoByToken")
    public User getUserInfoByToken(HttpServletRequest request) {
        // 通过 token 获取用户信息
        String token = request.getHeader("user_token_head");
        Assert.notNull(token, "用户未登录");
        Integer id = JwtUtils.getUserId(token);
        return userService.getUserInfoById(id);
    }

    @RequestMapping("/getAuthorByBlogId")
    public User getAuthorByBlogId(Integer blogId) {
        // 通过 token 获取用户信息
        Assert.notNull(blogId, "blogId 不合法：" + blogId);
        return userService.getAuthorByBlogId(blogId);
    }
}
